package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = getDateList(begin, end);

        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date -> {
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of( date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            //查询date日期对应的营业额
            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        });

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        dateList.forEach(date -> {
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", LocalDateTime.of( date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            //查询指定日期的注册用户数量
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);

            map.put("beginTime",null);
            Integer totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
        });

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

        for (LocalDate date : dateList) {
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", LocalDateTime.of( date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer totalOrder = ordersMapper.countByMap(map);
            orderCountList.add(totalOrder);


            map.put("status", Orders.COMPLETED);
            Integer validOrder = ordersMapper.countByMap(map);
            validOrderCountList.add(validOrder);

            //获取区间订单总数----写法一
            totalOrderCount += totalOrder;
            validOrderCount += validOrder;
        }
        //获取区间订单总数----其他写法
//        totalOrderCount = orderCountList.stream().reduce(new BinaryOperator<Integer>() {
//            @Override
//            public Integer apply(Integer num1, Integer num2) {
//                return num1 + num2;
//            }
//        }).get();

        //totalOrderCount = orderCountList.stream().reduce((num1, num2) -> num1 + num2).get();
        //totalOrderCount = orderCountList.stream().reduce(0,Integer::sum);

        //lambda表达式使用totalOrderCount += orderCount;会出现安全性问题
//        dateList.forEach(date -> {
//            Map<String, Object> map = new HashMap<>();
//            map.put("beginTime", LocalDateTime.of( date, LocalTime.MIN));
//            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
//            Integer orderCount = ordersMapper.countByMap(map);
//            orderCountList.add(orderCount);
//
//            map.put("status", Orders.COMPLETED);
//            Integer validOrderCount = ordersMapper.countByMap(map);
//            validOrderCountList.add(validOrderCount);
//        });

//        Map<String, Object> map = new HashMap<>();
//        map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN));
//        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX));
//        Integer totalOrderCount = ordersMapper.countByMap(map);
//
//        map.put("status", Orders.COMPLETED);
//        Integer validOrderCount = ordersMapper.countByMap(map);

        double orderCompletionRate =  0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .build();
    }

    /**
     * 销量排名
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", Orders.COMPLETED);
        map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN));
        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX));
        List<GoodsSalesDTO> salesTop10 = ordersMapper.getSalesTop10(map);
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 获取指定日期范围内的日期列表
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.isAfter(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        return dateList;
    }
}
